<?php
/**
 * Created by PhpStorm.
 *
 * Date: 2019-08-16
 * Time: 09:50
 * User: ghost <ghost@ghost-ai.com>
 */

namespace App\Http\Controllers\Index;



use App\Http\Controllers\Controller;
use App\Repositories\ArticleLabelRepositories;
use App\Repositories\ArticleRepositories;
use Exception;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\Request;
use Illuminate\View\View;


class AppController extends Controller
{
	
	/**
	 * 首页
	 *
	 * @param ArticleRepositories $articleRepositories
	 * @return Factory|View
	 */
    public function index(ArticleRepositories $articleRepositories)
    {
        $list = $articleRepositories->getPaginate(15);
        
        return view('home.app',['list'=>$list]);
    }
	
	/**
	 * 详情页面
	 *
	 * @param int $id
	 * @param ArticleRepositories $articleRepositories
	 * @return Factory|View
	 */
    public function details($id,ArticleRepositories $articleRepositories)
    {

    	try{
		    $res = $articleRepositories->getById($id );
		
		    $previousPostID = $articleRepositories->getModel()->query()->where('id', '<', $res->id)->max('id');
		
		    // 同理，获取 “下一篇” 的 ID
		    $nextPostId = $articleRepositories->getModel()->query()->where('id', '>', $res->id)->min('id');
		
		
		    $data['info'] = $res;
		
		    $data['previousArticle'] = $articleRepositories->getModel()->query()->where(['id'=>$previousPostID])->first(['id','title']) ?? [];
		    $data['nextArticle'] = $articleRepositories->getModel()->query()->where(['id'=>$nextPostId])->first(['id','title']) ?? [];
		    
		    
		    return view('home.details',['data'=>$data]);
	    }catch (Exception $exception)
	    {
	       return abort(404);
	    }
     
    }
	
	
	/**
	 * 分类筛选
	 *
	 * @param ArticleRepositories $articleRepositories
	 * @param int $id
	 *
	 * @return Factory|View
	 */
    public function category(ArticleRepositories $articleRepositories,int $id)
    {
        $where = ['category_id'=>$id];
        $list = $articleRepositories->getPaginate(4,$where);

        return view('home.app',['list'=>$list]);
    }
	
	/**
	 * 搜索筛选
	 *
	 * @param ArticleRepositories $articleRepositories
	 * @param Request $request
	 *
	 * @return Factory|View
	 */
    public function search(ArticleRepositories $articleRepositories,Request $request)
    {
        $search = $request->get ('search');
        $list = $articleRepositories->getSearch($search,4);

        return view('home.app',['list'=>$list]);
    }
}
